var $goodsTable, $goodsForm, $goodsAddBtn, $goodsSaveBtn, $goodsCancleBtn, $containersTable, $containersForm, $containersAddBtn, $containersSaveBtn, $containersCancleBtn, $containersBatchDelete, $containersCheckAll, $attachedTable, $attachedForm, $attachedAddBtn, $attachedSaveBtn, $attachedCancleBtn;
/**
 * 以下三个变量分别代表三个表单中对应input的ID，在点击保存时会把input#id的value值填写到对应的表格input框中
 * */
////序号，合同商品项目序号，商品编号，商品名称，计价数量，计价单位，装箱单备注内容
var goodsFields;
var containersFields = ["containerNo", "sizeShow", "containerWeight"];
var attachedFields = ["suifudan_co", "suifudan_no"];
//初始化按钮
$(document).ready(function () {
    initWebDomState();
    $goodsAddBtn.click(
        {
            show: true,
            addBtn: $goodsAddBtn,
            saveBtn: $goodsSaveBtn,
            cancleBtn: $goodsCancleBtn,
            form: $goodsForm
        },
        function (event) {
            addBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                             event.data.cancleBtn,
                             event.data.form, $(event.currentTarget));
            //设置默认的原产国(出口：142)，目的国（进口:142）
            if ($.fn.order.isExport) {
                $goodsForm.find("#origin_country_code").parent().dropdown("set selected", "142");
            } else {
                $goodsForm.find("#destination_code").parent().dropdown("set selected", "142");
            }
            //设置默认征免，监管方式为"一般贸易"，设置成:照章征免(1)
            if ($("input[name='trade_mode_code']").val() == "0110") {
                if ($.fn.order.isGeneralTrade) {
                    $goodsForm.find("#levyModeCode").parent().dropdown("set selected", "1");
                } else if ($.fn.order.isProcessTrade) {
                    $goodsForm.find("#levyModeCode").parent().dropdown("set selected", "3");
                }
            }
        }
    );
    $goodsSaveBtn.click(
        {
            show: false,
            addBtn: $goodsAddBtn,
            saveBtn: $goodsSaveBtn,
            cancleBtn: $goodsCancleBtn,
            form: $goodsForm,
            table: $goodsTable,
            field: goodsFields
        },
        function (event) {
            saveBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                              event.data.cancleBtn,
                              event.data.form, event.data.table, event.data.field,
                              $(event.currentTarget));
            InitFunctions.scrollCommodityBody();
        }
    );
    $goodsCancleBtn.click(
        {
            show: false,
            addBtn: $goodsAddBtn,
            saveBtn: $goodsSaveBtn,
            cancleBtn: $goodsCancleBtn,
            form: $goodsForm
        },
        function (event) {
            cancleBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                                event.data.cancleBtn,
                                event.data.form, $(event.currentTarget));
        }
    );
    $containersAddBtn.click(
        {
            show: true,
            addBtn: $containersAddBtn,
            saveBtn: $containersSaveBtn,
            cancleBtn: $containersCancleBtn,
            form: $containersForm
        },
        function (event) {
            addBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                             event.data.cancleBtn,
                             event.data.form, $(event.currentTarget));
        }
    );
    $containersSaveBtn.click(
        {
            show: false,
            addBtn: $containersAddBtn,
            saveBtn: $containersSaveBtn,
            cancleBtn: $containersCancleBtn,
            form: $containersForm,
            table: $containersTable,
            field: containersFields
        },
        function (event) {
            var containerNo = event.data.form.find("#containerNo").val();
            //柜号为空或有重复柜号时不添加
            if ($containersTable.find("tr").hasClass("active")) {
                if (!containerNo || new RegExp(".+" + containerNo + ".+").test(
                        $containersTable.find("tr:not(.active)").text())) {
                    event.data.cancleBtn.click();
                    return;
                }
            } else {
                if (!containerNo || new RegExp(".+" + containerNo + ".+").test(
                        $containersTable.text())) {
                    event.data.cancleBtn.click();
                    return;
                }
            }

            saveBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                              event.data.cancleBtn,
                              event.data.form, event.data.table, event.data.field,
                              $(event.currentTarget));
            InitFunctions.containerOperations();
        }
    );
    $containersCancleBtn.click(
        {
            show: false,
            addBtn: $containersAddBtn,
            saveBtn: $containersSaveBtn,
            cancleBtn: $containersCancleBtn,
            form: $containersForm
        },
        function (event) {
            cancleBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                                event.data.cancleBtn,
                                event.data.form, $(event.currentTarget));
        }
    );
    $attachedAddBtn.click(
        {
            show: true,
            addBtn: $attachedAddBtn,
            saveBtn: $attachedSaveBtn,
            cancleBtn: $attachedCancleBtn,
            form: $attachedForm
        },
        function (event) {
            addBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                             event.data.cancleBtn,
                             event.data.form, $(event.currentTarget));
        }
    );
    $attachedSaveBtn.click(
        {
            show: false,
            addBtn: $attachedAddBtn,
            saveBtn: $attachedSaveBtn,
            cancleBtn: $attachedCancleBtn,
            form: $attachedForm,
            table: $attachedTable,
            field: attachedFields
        },
        function (event) {
            saveBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                              event.data.cancleBtn,
                              event.data.form, event.data.table, event.data.field,
                              $(event.currentTarget));
        }
    );
    $attachedCancleBtn.click(
        {
            show: false,
            addBtn: $attachedAddBtn,
            saveBtn: $attachedSaveBtn,
            cancleBtn: $attachedCancleBtn,
            form: $attachedForm
        },
        function (event) {
            cancleBtnClick.call(this, event.data.show, event.data.addBtn, event.data.saveBtn,
                                event.data.cancleBtn, event.data.form, $(event.currentTarget))
        }
    );
    // BlurActions.bind();
});
/**
 * 初始化页面dom
 */
function initWebDomState() {
    $goodsForm = $("#commodities");
    $goodsTable = $goodsForm.nextAll("table");
    $goodsAddBtn = $("#goodsAdd");
    $goodsSaveBtn = $("#goodsSave");

    $goodsCancleBtn = $("#goodsCancle");
    $goodsForm.hide();
    $goodsSaveBtn.hide();
    $goodsCancleBtn.hide();
    $containersForm = $("#declaContainers");
    $containersTable = $containersForm.nextAll("table");
    $containersAddBtn = $("#containersAdd");
    $containersSaveBtn = $("#containersSave");
    $containersCancleBtn = $("#containersCancle");
    $containersBatchDelete = $("#containersBatch");
    $containersCheckAll = $("#containersCheckAll");
    $containersForm.hide();
    $containersSaveBtn.hide();
    $containersCancleBtn.hide();
    $attachedForm = $("#suiFuDans");
    $attachedTable = $attachedForm.nextAll("table");
    $attachedAddBtn = $("#attachedAdd");
    $attachedSaveBtn = $("#attachedSave");
    $attachedCancleBtn = $("#attachedCancle");
    $attachedForm.hide();
    $attachedSaveBtn.hide();
    $attachedCancleBtn.hide();
    /*if ($goodsTable.find("thead tr th").eq(1).text() != "合同商品项目序号") {
     goodsFields = ["index_num", "code_t", "name", "count", "unit",
     "packinglist_remark"];
     } else {
     goodsFields = ["index_num", "contractNumber", "code_t", "name", "count", "unit",
     "packinglist_remark"];
     }*/
    if ($.fn.order.isExport) {
        if ($.fn.order.isProcessTrade) {
            goodsFields = ["index_num", "record_id", "code_t", "name", "count", "unit",
                           "packinglist_remark"];
        } else if ($.fn.order.isGeneralTrade) {
            goodsFields = ["index_num", "code_t", "name", "count", "unit",
                           "packinglist_remark"];
        }
    } else if (!$.fn.order.isExport) {
        if ($.fn.order.isProcessTrade) {
            goodsFields = ["index_num", "contractNumber", "code_t", "name", "count", "unit",
                           "total_price"];
        } else if ($.fn.order.isGeneralTrade) {/*一般贸易*/
            goodsFields = ["index_num", "code_t", "name", "count", "unit",
                           "total_price"];
        }
    }
    //将页面列表中初始化的修改和删除按钮绑定上相应点击事件
    $.each([$goodsTable, $containersTable, $attachedTable], function (i, n) {
        n.find(".primary.basic.button").click(updateBtnClick);
        n.find(".negative.basic.button").click(deleteBtnClick);
    });
    $goodsTable.find(".purple.basic.button").click(copyBtnClick);
    $goodsTable.find(".black.basic.button").click(upBtnClick);
    $goodsTable.find(".brown.basic.button").click(downBtnClick);
    //将柜表数据中的柜型转换成中文值
    var containerTypes = {};
    $.each(DROPDOWN_DATA.containerType, function (i, n) {
        containerTypes[n.code] = n.name;
    });
    $.each($containersTable.find("tr:gt(0)"), function (i, n) {
        var $td = $(n).find("td:eq(1)");
        $td.text(containerTypes[$td.text()]);
    });
    //复制按钮绑定事件
    $("#copyBtn").click(function () {
        var id = $("input[name='id']").val();
        if (id) {
            var compareTemplateTip = layer.confirm('对旧数据进行修改时，被修改过的数据会显示亮色底纹进行区分显示', {
                btn: ['确定'] //按钮
            }, function () {
                location.href = "copy?id=" + id;
                layer.close(compareTemplateTip);
            });

        } else {
            layer.alert("只能在修改页面进行复制操作!");
        }
    });
    //一般贸易不能填写合同商品项目序号
    var record_id_readonly = $("input[name='record_id']").attr("readonly");
    if (record_id_readonly == "readonly") {
        $("#contractNumber").attr("readonly", "readonly");
    }
    //计算商品信息
    goodsCalc($goodsTable);
    //批量删除按钮绑定事件
    $containersBatchDelete.on("click", function () {
        var $containersTableTbody = $containersTable.find("tbody");
        var $containersTableTbodyTr = $containersTableTbody.find("tr");

        var checkedCount = 0;
        $containersTableTbodyTr.each(function (i, n) {
            if ($(this).find("input[type=checkbox]").get(0).checked) {
                $(this).find(".negative.basic.button").click();
                checkedCount++;
            }
        });
        if (checkedCount <= 0) {
            alert("请选择需要删除的柜号");
        }
        if ($containersCheckAll.get(0).checked) {
            $containersCheckAll.get(0).checked = false;
        }
    });
    //柜号勾选全选按钮绑定事件
    $containersCheckAll.on("click", function () {
        var $containersTableTbody = $containersTable.find("tbody");
        var $containersTableTbodyTr = $containersTableTbody.find("tr");
        if ($(this).get(0).checked) {
            $containersTableTbodyTr.find("input[type=checkbox]").each(function (i, n) {
                $(this).get(0).checked = true;
            });
        } else {
            $containersTableTbodyTr.find("input[type=checkbox]").each(function (i, n) {
                $(this).get(0).checked = false;
            });
        }
    });

}
/**
 * 点击添加按钮是否展示对应表单
 * @param show  展示或者隐藏 boolean值
 * @param addBtn  添加按钮
 * @param saveBtn 保存按钮
 * @param cancleBtn 取消按钮
 * @param form 表单
 */
function doShowForm(show, addBtn, saveBtn, cancleBtn, form, target) {
    var dtd = $.Deferred();
    if (show) {
        saveBtn.show();
        cancleBtn.show();
        addBtn.hide();
        form.show();
    } else {
        if ($(form).attr("id") == "commodities" && target.attr("id") == "goodsSave" && isShowTip) {
            var record = new Object();
            record.code_t = $(form).find("#code_t").val();
            record.code_s = $(form).find("#code_s").val();
            record.count = $(form).find("#count").val();
            record.legal_count = $(form).find("#legal_count").val();
            record.unit_price = $(form).find("#unit_price").val();
            var json = JSON.stringify(record);
            $.ajax({
                       url: "/business/validateGoodsCodeCache",
                       dataType: "json",
                       type: "POST",
                       data: "record=" + json,
                       success: function (data) {
                           console.log(data);
                           var msg = "商品项[" + record.code_t + record.code_s + "]\n";
                           if (data != 0) {
                               data += "";
                               if (data.indexOf("1") != -1) {
                                   msg += "（计价数量／法定数量）大于正常范围。\n";
                               }
                               if (data.indexOf("2") != -1) {
                                   msg += "（计价数量／法定数量）小于正常范围。\n";
                               }
                               if (data.indexOf("3") != -1) {
                                   msg += "单价大于正常范围。\n";
                               }
                               if (data.indexOf("4") != -1) {
                                   msg += "单价小于正常范围。\n";
                               }
                               layer.confirm(msg + "是否修改？", {
                                   btn: ['确认', '取消']
                               }, function () {
                                   layer.closeAll('dialog');
                                   $(form).find("#count").focus();
                                   dtd.resolve();
                               }, function () {
                                   layer.closeAll('dialog');
                                   dtd.reject();
                                   saveBtn.hide();
                                   cancleBtn.hide();
                                   addBtn.show();
                                   form.hide();
                               });
                           } else {
                               dtd.reject();
                               saveBtn.hide();
                               cancleBtn.hide();
                               addBtn.show();
                               form.hide();
                           }
                       },
                       error: function (a, b, c) {
                           console.log(b);
                       }
                   });
        } else {
            dtd.reject();
            saveBtn.hide();
            cancleBtn.hide();
            addBtn.show();
            form.hide();
            isShowTip = true;
        }
    }
    return dtd.promise();
}
/**
 * 取消按钮
 */
var cancleBtnClick = function (show, addBtn, saveBtn, cancleBtn, form, target) {
    doShowForm(show, addBtn, saveBtn, cancleBtn, form, target);
    form.find("input").val("").parent().removeClass("error");
    form.find(".text").text("").parent().removeClass("error");
};

/**
 * 添加按钮
 */
var addBtnClick = function (show, addBtn, saveBtn, cancleBtn, form, target) {
    $(".compareTip").removeClass("compareTip");
    doShowForm(show, addBtn, saveBtn, cancleBtn, form, target);
    if (addBtn == $goodsAddBtn) {
        var index = $goodsTable.find("tbody tr").length + 1;
        form.find("#index_num").val(index);
    }
};
/**
 * 关系按钮
 */
var relationBtnClick = function () {
    var $table = $(".relationTable");
    var $showRelationTable = $(".showRealationTable");
    var $goodsTable = $("#commodities").nextAll("table");
    var $goodsTr = $goodsTable.find("tbody tr");
    var $body = $showRelationTable.find("tbody");
    if ($table.css("display") == "none") {
        $table.show();
        if ($body.find("tr").length - 4 >= $goodsTr.length) {
            $(".relation-sure").addClass("disabled");
        } else {
            $(".relation-sure").removeClass("disabled");
        }
    }
};

/**
 * 去除字符串两边的空格
 * @returns {string}
 */
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 保存按钮通用主体方法
 */
/**
 * isShowTip 是否提示毛净重合理范围
 * @type {boolean}
 */
var isShowTip = true;
var commonSave = function (show, addBtn, saveBtn, cancleBtn, form, table, fields, target) {
    var commonDeferredFunc = function () {
        var $tr = formDataToTableInput(form, table);
        if ($tr.find("td").length != 0) {//修改
            $.each(fields, function (i, n) {
                /*$tr.find("td:eq(" + i + ")").text(form.find("#" + n).val());*/
                if (n == "total_price") {
                    $tr.find("td:eq(" + i + ")").text(form.find("#" + n).val() + " "
                                                      + form.find("#currency").val());
                } else if (n == 'code_t') {
                    $tr.find("td:eq(" + i + ")").text(form.find("#code_t").val()
                                                      + form.find("#code_s").val());
                } else if (n == 'containerNo') {
                    $tr.find("td:eq(" + i + ")").html("<input type='checkbox'/>&nbsp;"
                                                      + form.find("#" + n).val().trim());
                } else {
                    $tr.find("td:eq(" + i + ")").text(form.find("#" + n).val().trim());
                }
            });
        } else {//添加
            $.each(fields, function (i, n) {
                if (n == "total_price") {
                    $tr.append($("<td>").text(form.find("#" + n).val() + " "
                                              + form.find("#currency").val()));
                } else if (n == 'code_t') {
                    $tr.append($("<td>").text(form.find("#code_t").val()
                                              + form.find("#code_s").val()));
                } else {
                    if (n == "containerNo") {
                        $tr.append($("<td>").html("<input type='checkbox'/>&nbsp;" + form.find("#"
                                                                                               + n).val().trim()));
                    } else {
                        $tr.append($("<td>").text(form.find("#" + n).val().trim()));
                    }

                }
            });
            $tr.append(createOptionButtons($("<td>")));//操作区
            var index = $tr.find("input[type='hidden']").attr("name").indexOf("[");
            if ($tr.find("input[type='hidden']").attr("name").substr(0, index) != "commodities") {
                $tr.find(".black").hide();
                $tr.find(".brown").hide();
                $tr.find(".purple").hide();
            }
        }
        goodsCalc(table);
        var inputIdField;
        if ($.fn.order.isExport) {
            inputIdField =
            ['code_t', 'code_s', 'name', 'goods_mode', 'goods_mode_label', 'boxMark',
             'destination_code',
             'destination',
             'origin_country_code', 'origin_country', 'legalUnitCode', 'legal_unit',
             'unitCode', 'unit', 'secondUnitCode', 'second_unit'];

        } else {
            inputIdField =
            ['code_t', 'code_s', 'name', 'key_elements', 'key_elements_label',
             'destination_code',
             'destination',
             'origin_country_code', 'origin_country', 'legalUnitCode', 'legal_unit',
             'unitCode', 'unit', 'secondUnitCode', 'second_unit'];
        }
        $.each(form.find("input"), function (i, n) {
            if ($.inArray($(n).attr("id"), inputIdField) == -1) {
                if ($(n).prev().attr("id") == "code_t" || $(n).prev().attr("id") == "code_s") {
                    return;
                } else {
                    $(n).val("");
                    if ($(n).nextAll(".text").length && $(n).attr("type") == "hidden") {
                        $(n).nextAll(".text").text("");
                    }
                }
            }
        });
        if (!$.fn.order.isExport) {
            if ($.fn.order.isProcessTrade) {
                var regOne = /^C[0-9]{11}$/;
                var regTwo = /^B[0-9]{11}$/;
                var regThree = /^E[0-9]{11}$/;
                var recordIdVal = $(".allform").find("input[name='record_id']").val();
                if (regOne.test(recordIdVal) || regTwo.test(recordIdVal)
                    || regThree.test(recordIdVal)) {
                    $("#levyModeCode").parent().dropdown("set selected",
                                                         "3");
                }
            }

        }
    };
    doShowForm(show, addBtn, saveBtn, cancleBtn, form, target).done(function () {
        return false;
    }).fail(function () {
        commonDeferredFunc();
    });
};

/**
 * 浮点数的精确计算乘法
 * @param table
 */
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}
/**
 * 浮点数的精确计算
 * @param table
 */
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (accMul(arg1, m) + accMul(arg2, m)) / m;
    /*return (arg1 * m + arg2 * m) / m;*/
};
/**
 * 计算商品汇总
 * @param table
 */
var goodsCalc = function (table) {
    var totalNumber = 0;
    var totalGross = 0;
    var totalNet = 0;
    var totalPrice = 0;

    $.each($(table).find("tbody tr"), function (i, n) {
        $.each($(n).find("input[type='hidden']"), function (j, m) {
            var hiddenPrefix = $(m).attr("name").substr($(m).attr("name").indexOf(".") + 1);
            if (hiddenPrefix == 'goods_number') {
                /*totalNumber += Number($(this).val());*/
                totalNumber = accAdd($(this).val(), totalNumber);
            } else if (hiddenPrefix == 'goods_gross_weight') {
                /*totalGross += Number($(this).val());*/
                totalGross = accAdd($(this).val(), totalGross);
            } else if (hiddenPrefix == 'goods_net_weight') {
                /*totalNet += Number($(this).val());*/
                totalNet = accAdd($(this).val(), totalNet);
            } else if (hiddenPrefix == 'total_price') {
                /*totalPrice += Number($(this).val());*/
                totalPrice = accAdd($(this).val(), totalPrice);
            }
        });
    });
    var footTdLen = $(table).find("tfoot tr .detail").length;
    if (footTdLen == 1) {
        $(table).find("tfoot tr .detail").text(totalPrice);
    } else {
        $(table).find("tfoot tr .detail").eq(0).text(totalNumber);
        $(table).find("tfoot tr .detail").eq(1).text(totalGross);
        $(table).find("tfoot tr .detail").eq(2).text(totalNet);
        $(table).find("tfoot tr .detail").eq(3).text(totalPrice.toFixed(2));
    }
    //这个顺序很重要
    $(table).next("input[name='total_money']").val(totalPrice);

    /*form.find("input").val("");*/
    /*form.find(".text").text("");*/
};
/**
 * 点击保存按钮将表单中的信息添加到表格中
 * globalGoodsBool变量用来检测excel导入判断必填项有没有填全
 */
var globalGoodsBool = true;
var saveBtnClick = function (show, addBtn, saveBtn, cancleBtn, form, table, fields, target) {
    if (saveBtn == $goodsSaveBtn) {
        delete validationRules['goodsFormRule'].on;
        console.log($(".goodsForm").form.settings.on);
        console.log(validationRules['goodsFormRule']);
        $('.ui.goodsForm').form(validationRules['goodsFormRule']);
        var goodsValidBool = $('.ui.goodsForm').form('is valid');
        validationRules['goodsFormRule'].on = 'blur';
        $('.ui.goodsForm').form(validationRules['goodsFormRule']);
        $(".goodsForm").form.settings.on = 'blur';
        if (goodsValidBool) {
            var unitVal = $(form).find("#unitCode").val();
            var legalUnitVal = $(form).find("#legalUnitCode").val();
            var secondUnitVal = $(form).find("#secondUnitCode").val();
            if (unitVal == legalUnitVal) {
                var count = $(form).find("#count").val();
                var legal_count = $(form).find("#legal_count").val();
                if (count != legal_count) {
                    addShowErrors("计价数量和法定数量值不相等!");
                    return false;
                }
            }
            if (unitVal == secondUnitVal) {
                var count = $(form).find("#count").val();
                var second_count = $(form).find("#second_count").val();
                if (count != second_count) {
                    addShowErrors("计价数量和第二数量值不相等!");
                    return false;
                }
            }
            if (legalUnitVal == secondUnitVal) {
                var legal_count = $(form).find("#legal_count").val();
                var second_count = $(form).find("#second_count").val();
                if (legal_count != second_count) {
                    addShowErrors("法定数量和第二数量值不相等!");
                    return false;
                }
            }
            commonSave(show, addBtn, saveBtn, cancleBtn, form, table, fields, target);
            globalGoodsBool = true;
            validationRules['goodsFormRule'].on = 'blur';
        } else {
            globalGoodsBool = false;
            validationRules['goodsFormRule'].on = 'blur';
            $(".goodsForm").form.settings.on = 'blur';
            return false;
        }
    } else if (saveBtn == $containersSaveBtn) {
        delete validationRules['declaContainersFormRule'].on;
        $(".ui#declaContainers").form(validationRules['declaContainersFormRule']);
        var containersValidBool = $('.ui#declaContainers').form('is valid');
        if (containersValidBool) {
            commonSave(show, addBtn, saveBtn, cancleBtn, form, table, fields, target);
        } else {
            return false;
        }
    } else if (saveBtn == $attachedSaveBtn) {
        $('.ui#suiFuDans').form(validationRules['suiFuDansFormRules']);
        var attachedValidBool = $('.ui#suiFuDans').form('is valid');
        var $suifudanCo = $("#suifudan_co");
        var $suifudanCoVal = $suifudanCo.val();
        if (attachedValidBool) {
            if ($suifudanCoVal == "Y"
                && new RegExp($suifudanCoVal).test(
                    $("table[name = 'suifudanTable']").find("tr td:first").text())) {
                $attachedCancleBtn.click();
                return;
            }
            if ($suifudanCoVal == "Y") {
                $(".relationTable").show();
                $(".serial-Number").focus();
            }
            commonSave(show, addBtn, saveBtn, cancleBtn, form, table, fields, target);
        } else {
            return false;
        }
    }
};

/**
 * 通用修改事件
 */
var updateBtnClick = function () {
        var $form = $(this).parents("table").siblings("div[id]:first");
        //清理已选中修改的行
        var $activeTr = $(this).parents("table").find("tr.active");
        if ($activeTr.length != 0) {
            $activeTr.removeClass("active");
            $.each($form.find("input"), function (i, n) {
                $(n).val("")
            });
            $.each($form.find(".search>div.text"), function (i, n) {
                $(n).text("");
            });
        }
        var prefix = $form.attr("id");
        var $tr = $(this).parents("tr:first");
        var trHiddenInputs = $tr.find('input:hidden');
        var namePattern = /\.\w*$/;
        //收集表单数据
        var nameValues = {};
        $.each(trHiddenInputs, function (i, n) {
            var hiddenInput = $(n);
            var name = hiddenInput[0].name.match(namePattern)[0].replace(".", "");
            nameValues[name] = hiddenInput.val();
        });
        //给表单赋值
        var formInputs = $form.find('input[id]');
        $.each(formInputs, function (i, n) {
            var $formInput = $(n);
            var iid = $formInput.attr("id");
            var val = nameValues[iid];
            if (val == undefined) {
                return;
            }
            var $parentDiv = $formInput.parent();
            if ($parentDiv.hasClass("search selection dropdown")) {
                if (iid == 'code_t') {
                    $parentDiv.dropdown('set').text(val + nameValues.code_s);
                    $formInput.val(val);
                } else if (iid == 'code_s') {
                    $formInput.val(val);
                } else {
                    $parentDiv.dropdown('set selected', val);
                }
            } else {
                $formInput.val(val);
            }
        });

        //设置是修改第几行 doShowForm(show,addBtn,saveBtn,form)
        $tr.addClass("active");
        if (prefix == "commodities") {
            doShowForm(true, $goodsAddBtn, $goodsSaveBtn, $goodsCancleBtn, $goodsForm);
            addOrRemoveSecondRequired(
                nameValues['secondUnitCode'] != undefined && nameValues['secondUnitCode'] != '');
            $("html,body").animate({scrollTop: $("#commodities").offset().top}, 1);
        } else if (prefix == "declaContainers") {
            doShowForm(true, $containersAddBtn, $containersSaveBtn, $containersCancleBtn,
                       $containersForm);
        } else if (prefix == "suiFuDans") {
            doShowForm(true, $attachedAddBtn, $attachedSaveBtn, $attachedCancleBtn, $attachedForm);
        }
    }
    ;
/**
 * 刪除表格中的某一行设置表格中序号的值
 */
function reSetShowSerid(arg1, arg2) {
    var index = 1;
    $.each($(arg1), function (i, n) {
        $(n).find("td").eq(0).text(index);//设置表格中序列号的值
        index++;
    });
    if (arg2) {
        $("#" + arg2).val(index);
    }
}
/**
 * 设置删除某一行后表格行隐藏域的name属性的值
 */
function reSetArrNum(arg1) {
    $.each($(arg1), function (i, n) {
        $.each($(n).find("input[type=hidden]"), function (j, m) {
            var name = $(m).attr("name");
            $(m).attr("name",
                      name.substr(0, name.indexOf("[") + 1) + i + name.substr(name.indexOf("]")));
            if (name.substr(name.indexOf(".") + 1) == "index_num") {
                $(m).val(i + 1);
            }
        });
    });

}
/**
 * 点击商品删除按钮事件
 */
var deleteBtnClick = function () {
    var serialNum, formSerial, tbody, trId;
    trId = $(this).parent().parent("tr");//删除的那一行
    tbody = $(this).parent().parent().parent();//删除的那个表格的tbody
    $(trId).remove();
    serialNum = $(tbody).find("tr");
    var index = trId.find("input[type='hidden']").eq(1).attr("name").indexOf(".") + 1;
    var inputHiddenId = trId.find("input[type='hidden']").eq(1).attr("name").substr(index);
    if (inputHiddenId == "index_num") {
        formSerial = "index_num";
    }
    if ($(tbody).parent().hasClass("notAutoIncrease")) {
        reSetArrNum(serialNum);
    } else {
        reSetShowSerid(serialNum, formSerial);
        reSetArrNum(serialNum);
    }
    goodsCalc($goodsTable);
    InitFunctions.scrollCommodityBody();
    InitFunctions.scrollContainerBody();
    InitFunctions.collectContainerInfo();
};
/**
 * 数据从表单转移到表格，通过隐藏的input进行保存，如表单中有id属性，数组下标为0，它将保存进如表格的id[0]，如果有前缀为container,则会转为container[0].id
 * @param $from 获取数据的表单
 * @param $to 数据存储到的表格
 * @param prefix 隐藏域的前缀，对于列表数据可能存在前缀对应后台对象，默认值为$from参数对应的dom的id
 *
 */
var formDataToTableInput = function ($from, $to, prefix) {
    //如果是修改(表单div有attr属性)，则取得修改的行
    var $tr = $to.find("tbody tr.active");
    var isUpdate = $tr.length != 0;
    var index;//取下标
    if (isUpdate) {
        /*$.each($to.find("tbody tr"), function (i, n) {
         if ($(n).hasClass("active")) {
         index = i;
         index=$(n).find("td").eq(0).text()-1;
         }
         })*/
        var hiddenName = $tr.find("input[type='hidden']").attr("name");
        var startIndex = hiddenName.indexOf("[");
        var endIndex = hiddenName.indexOf("]");
        index = hiddenName.substring(startIndex + 1, endIndex);
    } else {
        index = $to.find("tbody tr").length;
    }
    prefix = prefix ? prefix : $from.attr("id");
    $tr = isUpdate ? $tr : $("<tr>");
    $.each($from.find("input"), function (i, n) {
        try {
            if ($(n).hasClass("search")) {
                return;
            }
            if (!$(n).attr("id")) {
                return;
            }
            var name = $.arrayNameCover($(n).attr("id"), index, prefix);
            var value = $(n).val();
            if (isUpdate) {
                $tr.find(":hidden[name='" + name + "']").val(value);
            } else {
                $tr.append($("<input>").attr(
                    {
                        name: name,
                        type: "hidden",
                        value: value
                    }));
                $to.find("tbody").append($tr);
            }
        } catch (e) {
            console.error($(n));
            throw e;
        }
    });
    if (isUpdate) {
        $tr.removeClass("active");
    }

    /*$to.find("tbody").append($tr);*/
    return $tr;
};
/**
 * 转为带数组下标的命名 ，如：index=0,prefix=container，返回值为container[0].name，如果prefix为空，返回name[0]
 * @param index 下标
 * @param name 命名
 * @param prefix  前缀
 */
$.arrayNameCover = function (name, index, prefix) {
    if (!name) {
        throw new Error("name不能为空，无法生成命名，请检查代码!");
    }
    if (prefix) {
        return prefix + "[" + index + "]." + name;
    } else {
        return name + "[" + index + "]";
    }
};
/**
 * 表格行上移
 */
var upBtnClick = function () {
    var tbody = $(this).parents("tbody");
    var upTr = $(this).parents("tr");
    var prev = $(upTr).prev("tr");
    if ($(prev).length) {
        $(upTr).insertBefore($(prev));
        var allTr = $(tbody).find("tr");
        $.each(allTr, function (i, n) {
            $(n).find("td").eq(0).text(i + 1);
            $.each($(n).find("input[type='hidden']"), function (j, m) {
                var name = $(m).attr("name");
                var dotIndex = name.indexOf(".");
                var startIndex = name.indexOf("[");
                var endIndex = name.indexOf("]");
                if (name.substr(dotIndex + 1) == "index_num") {
                    $(m).val(i + 1);
                }
                $(m).attr("name", name.substr(0, startIndex + 1) + (i) + name.substr(endIndex));
            });
        });
        if ($(upTr).hasClass("active")) {
            $goodsForm.find("#index_num").val($(upTr).find("td").eq(0).text());
        }
    } else {
        layer.alert("不可操作");
        return false;
    }
};
/**
 * 表格行下移
 */
var downBtnClick = function () {
    var tbody = $(this).parents("tbody");
    var downTr = $(this).parents("tr");
    var next = $(downTr).next("tr");
    if ($(next).length) {
        $(downTr).insertAfter($(next));
        var allTr = $(tbody).find("tr");
        $.each(allTr, function (i, n) {
            $(n).find("td").eq(0).text(i + 1);
            $.each($(n).find("input[type='hidden']"), function (j, m) {
                var name = $(m).attr("name");
                var dotIndex = name.indexOf(".");
                var startIndex = name.indexOf("[");
                var endIndex = name.indexOf("]");
                if (name.substr(dotIndex + 1) == "index_num") {
                    $(m).val(i + 1);
                }
                $(m).attr("name", name.substr(0, startIndex + 1) + (i) + name.substr(endIndex));
            });
        });
        if ($(downTr).hasClass("active")) {
            $goodsForm.find("#index_num").val($(downTr).find("td").eq(0).text());
        }
    } else {
        layer.alert("不可操作");
        return false;
    }

}
/**
 * 表格行复制
 */
var copyBtnClick = function () {
    var tbody = $(this).parents("tbody");
    var currentTr = $(this).parents("tr");
    var copyTr = $(currentTr).clone(true);
    var len = $(tbody).find("tr").length;
    $(copyTr).find("td").eq(0).text(len + 1);
    $.each($(copyTr).find("input[type='hidden']"), function (i, n) {
        var name = $(n).attr("name");
        var start = name.indexOf("[");
        var end = name.indexOf("]");
        $(n).attr("name",
                  name.substr(0, start + 1) + ($(copyTr).find("td").eq(0).text() - 1)
                  + name.substr(end));
        if (name.substr(end + 1 + 1) == "index_num") {
            $(n).val($(copyTr).find("td").eq(0).text());
        } else if (name.substr(end + 1 + 1) == "id") {
            n.value = "";
        }
    });
    $(tbody).append($(copyTr));
    goodsCalc($goodsTable);
    InitFunctions.scrollCommodityBody();
}
/**
 * 创建操作按钮区
 * @param $dom
 * @returns {*|void}
 */
var createOptionButtons = function ($dom) {
    var updateBtn = $("<button class=\"ui mini primary basic button\">修改</button>").click(
        updateBtnClick);
    var deleteBtn = $("<button class=\"ui mini negative basic button\">删除</button>").click(
        deleteBtnClick);
    var upBtn = $(
        "<button class=\"ui mini black basic  button \"><i class=\"arrow up icon\"></i></button>")
        .click(
        upBtnClick);
    ;
    var downBtn = $(
        "<button class=\"ui mini brown basic  button \"><i class=\"arrow down icon\"></i></button>")
        .click(
        downBtnClick);
    var copyBtn = $(
        "<button class=\"ui mini purple basic  button \">复制</button>").click(
        copyBtnClick);
    return $dom.append(updateBtn).append(deleteBtn).append(copyBtn).append(upBtn).append(downBtn);
};

var readMode_readGoods = function (arg) {
    var $tr = $(arg);
    /*var $tr = $(event.target).parent("tr");*/
    var $inputs = $tr.find("input");
    for (var i = 0; i < $inputs.length; i++) {
        var $input = $($inputs[i]);
        var name = $input.attr("name");
        var val = $input.val();
        var selector = name.substring(name.indexOf(".") + 1);
        var $showValueDiv = $("div[goods_ele_selector='" + selector + "']");
        var _dropdownDataMap = {
            "unitCode": "#unit",
            "destination_code": "#destination_code",
            "origin_country_code": "#origin_country_code",
            "legalUnitCode": "#legal_unit",
            "levyModeCode": "#levymode",
            "currencyCode": "#currency",
            "secondUnitCode": "#second_unit"
        };

        if (_dropdownDataMap[selector] != undefined) {
            var dConfig = undefined;
            var _key = _dropdownDataMap[selector];
            for (var j = 0; j < dropdownConfig.length; j++) {
                var __config = dropdownConfig[j];
                if (__config.key == _key) {
                    dConfig = __config;
                    break;
                }
            }
            var configDataArr = dConfig.data;
            if (configDataArr != undefined && configDataArr.length > 0) {
                for (j = 0; j < configDataArr.length; j++) {
                    var _data = configDataArr[j];
                    if (_data.code == val) {
                        val = _data.name;
                        break;
                    }
                }
            }
        }
        $showValueDiv.text(val);
        $showValueDiv.attr("title", val);
    }
    $tr.siblings("tr").removeClass("goods_background_color");
    $tr.addClass("goods_background_color");
};
var changeBackGroundColor = function (event) {
    var $tr = $(event.target).parent("tr");
    $tr.siblings("tr").removeClass("goods_background_color");
    $tr.addClass("goods_background_color");
}
/**
 * 只读模式下，查阅商品资料的事件绑定
 */
var readMode_readGoods_bind = function () {
    var $table = $("#goodsTable");
    if ($table.length > 0) {
        var $trs = $table.find("tbody tr");
        readMode_readGoods($trs.eq(0));
        $.each($trs, function (i, n) {
            var $tr = $(n);
            $tr.addClass("pointer");
            $tr.click(
                {
                    arg: $(this)
                },
                function (event) {
                    readMode_readGoods.call(this, event.data.arg);
                });
            $tr.click(readMode_readGoods);
            $tr.click(changeBackGroundColor);
        });
    }
};

var addOrRemoveSecondRequired = function (addRequired) {
    if (addRequired) {
        // $("#secondUnitCode").parent().removeDisabledClass();
        $("#second_count").parent().removeDisabledClass();
        //给第二数量加上限制
        setInputsRequired(
            {
                "#secondUnitCode": {
                    required: true,
                    ref_form_id: ".ui.goodsForm",
                    ref_rule: "goodsFormRule",
                    errorText: "第二数量为必填项"
                },
                "#second_count": {
                    required: true,
                    ref_form_id: ".ui.goodsForm",
                    ref_rule: "goodsFormRule",
                    errorText: "第二计量单位为必填项"
                }
            }
        );
    } else {
        // $("#secondUnitCode").parent().removeClass("error").addDisabledClass();
        $("#second_count").parent().removeClass("error").addDisabledClass();
        $("#secondUnitCode").parent().dropdown('set text', '');
        $("#second_unit").val('');
        $("#second_count").val("");
        $("#secondUnitCode").val("");
        //取消第二数量的限制
        setInputsRequired(
            {
                "#secondUnitCode": {
                    required: false,
                    ref_form_id: ".ui.goodsForm",
                    ref_rule: "goodsFormRule"
                },
                "#second_count": {
                    required: false,
                    ref_form_id: ".ui.goodsForm",
                    ref_rule: "goodsFormRule"
                }
            }
        );
    }
}

/**
 * 展示联系方式
 */
function showContactWay(did, role) {
    $.ajax({
               url: "/business/getContactWay",
               cache: false,
               dataType: 'json',
               data: {"did": did, "role": role},
               success: function (data) {
                   if (data.result) {
                       var user = data.data;
                       var phone = user.uMobile;
                       if (!phone) {
                           phone = '暂无';
                       }
                       jw.alert("联系人：" + user.uName + "<br/>联系电话：" + phone);
                   } else {
                       jw.alert(data.msg);
                   }
               }
           });
}

